import React, { Suspense } from "react";
import PageLoading from "@/components/PageLoading";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import GridContent from "@/components/PageHeaderWrapper/GridContent";
import { Tabs, Icon, Tooltip, Form, message, Layout, Button } from "antd";
import GraphList from "@/pages/KnowledgeGraph/list/index";
import TabPaneModal from "@/pages/KnowledgeGraph/tabCategory/tabPaneModal";
import EditPaneModal from "./editPaneModal";
import { connect } from "dva";
import styles from "./tabCategory.less";
import UserSession from "@/UserSession";
import { knowledgeListAtlas, knowledgeAtlasCategoryInfo } from '@/services/knowledgegraph';
import { postGraphCategoryAdd, postGraphCategoryEdit, getGraphCategoryDel } from "@/services/knowledgeCategory";
import ReferenceTemplate from './referenceTemplate';

class TabCategory extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			tabPaneList: [],
			graphList: [],
			graphTotal: 0,
			graphLoading: false,
			graphCategoryId: "",
			current: 1,
		};
	}

	componentDidMount() {
		this.getTabList();
	}

	/**
	 * 获取分类
	 */
	getTabList = async () => {
		const { dispatch, match: { params: { id } } } = this.props;
		if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeAtlasCategoryInfo({ rootCategoryId: id });
			// console.log(res);
			this.setState({ tabPaneList: res }, () => {
				this.fetchGraphList(15, 1);
			});
		} else {
			dispatch({
				type: "knowledgeGraphList/getGraphCategory",
				payload: {
					categoryId: id,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					// console.log(res);
					this.setState({ tabPaneList: res }, () => {
						this.fetchGraphList(15, 1);
					});
				},
			});
		}
	};

	/**
	 * 分类管理
	 * @returns {*}
	 */
	tabPaneManage = () => {
		const { tabPaneList } = this.state;
		this.TabPaneModal.openModal(tabPaneList);
	};

	addManage = () => {
		this.EditPaneModalRef.openModal()
	}

	editManage = () => {
		const { tabPaneList, graphCategoryId } = this.state;
		let row = tabPaneList.filter(item => item.id == graphCategoryId);
		this.EditPaneModalRef.openModal(row[0]);
	}

	setCategory = async (name, categoryId) => {
		const { dispatch, match: { params: { id }, }, } = this.props;
		let obj = { name, rootCategoryId: id };
		let res = { code: -1, data: false, msg: '操作成功' };
		if (categoryId) {
			obj.id = categoryId;
			res = await postGraphCategoryEdit(obj)
		} else {
			res = await postGraphCategoryAdd(obj);
		};
		if (res.code === 0) {
			message.success('操作成功')
			this.EditPaneModalRef.closeModal()
		}
	}

	delManage = async () => {
		const { tabPaneList, graphCategoryId } = this.state;
		let row = tabPaneList.filter(item => item.id == graphCategoryId);
		let res = await getGraphCategoryDel({ id: row[0]?.id })
		if (res.code === 0) {
			message.success("操作成功");
			this.setState({ graphCategoryId: "" }, () => this.getTabList())
		}
	}

	/**
	 * 切换分类
	 * @returns {*}
	 */
	changeTab = (key) => {
		this.setState({ graphCategoryId: key }, () => {
			this.fetchGraphList(15, 1);
		});
	};

	/**
	 * 根据分类获取相应图谱
	 * @returns {*}
	 */
	fetchGraphList(limit, page) {
		const { graphCategoryId, tabPaneList } = this.state;
		const { dispatch, match: { params: { id }, }, } = this.props;
		this.setState({ graphLoading: true, current: page }, async () => {
			let tegoryListId = tabPaneList.map((item) => item.id);
			if (graphCategoryId !== "" && tegoryListId.indexOf(graphCategoryId) === -1) {
				let tegoryId = tegoryListId[0];
				if (UserSession.isSystemKnowledge()) {
					let res = await knowledgeListAtlas({
						size: limit,
						current: page,
						rootCategoryId: id,
						categoryId: tegoryId,
					});
					this.setState({
						graphTotal: res.total,
						graphList: res.records,
						graphLoading: false,
					});
				} else {
					dispatch({
						type: "knowledgeGraphList/fetchList",
						payload: {
							size: limit,
							current: page,
							rootCategoryId: id,
							categoryId: tegoryId,
							urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
						},
						callback: (res) => {
							this.setState({
								graphTotal: res.total,
								graphList: res.records,
								graphLoading: false,
							});
						},
					});
				}
			} else {
				if (UserSession.isSystemKnowledge()) {
					let res = await knowledgeListAtlas({
						size: limit,
						current: page,
						rootCategoryId: id,
						categoryId: graphCategoryId,
					});
					this.setState({
						graphTotal: res.total,
						graphList: res.records,
						graphLoading: false,
					});
				} else {
					dispatch({
						type: "knowledgeGraphList/fetchList",
						payload: {
							size: limit,
							current: page,
							rootCategoryId: id,
							categoryId: graphCategoryId,
							urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
						},
						callback: (res) => {
							this.setState({
								graphTotal: res.total,
								graphList: res.records,
								graphLoading: false,
							});
						},
					});
				}
			}
		});
	}

	/**
	 * 子组件传值
	 * @returns {*}
	 */
	fetchGraphListByPage = (limit, page) => {
		this.fetchGraphList(limit, page);
	};

	reference = () => {
		const { graphCategoryId } = this.state;
		if (this.referenceTemplateRef) {
			this.referenceTemplateRef.init({ type: "classify", id: graphCategoryId })
		}
	}

	render() {
		const { tabPaneList, graphList, graphTotal, graphLoading, graphCategoryId } = this.state;
		const { match: { params: { id } }, location } = this.props;
		const operations = UserSession.isSystemKnowledge() && graphCategoryId !== '' ? (
			<Button icon="block" style={{ margin: '12px 0' }} onClick={this.reference}>引用</Button>
		) : UserSession.whetherCanDelete() ? null : (
			<span style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
				{/* <Button icon='unordered-list' style={{ margin: '12px 0' }} onClick={this.tabPaneManage}>分类管理</Button> */}
				<Tooltip placement="bottom" title="新增分类">
					<Button icon='plus' style={{ margin: '12px 0' }} onClick={this.addManage}></Button>
				</Tooltip>
				{graphCategoryId !== '' ? (
					<>
						<Tooltip placement="bottom" title="编辑分类名称">
							<Button icon='form' style={{ margin: '12px 0' }} onClick={this.editManage}></Button>
						</Tooltip>
						<Tooltip placement="bottom" title="删除分类">
							<Button icon='delete' style={{ margin: '12px 0' }} onClick={this.delManage}></Button>
						</Tooltip>
					</>
				) : null}
			</span>
		);

		return (
			<GridContent>
				<Suspense fallback={<PageLoading />}>
					<div style={{ padding: "0 10px 15px" }} className={styles.tabCategoryCard}>
						<Tabs
							tabBarExtraContent={operations}
							defaultActiveKey={""}
							onChange={this.changeTab}
						>
							<Tabs.TabPane key={""} tab={"全部"}>
								<GraphList
									graphCategoryId={""}
									tabPaneList={tabPaneList}
									list={graphList}
									current={this.state.current}
									total={graphTotal}
									graphLoading={graphLoading}
									fetchGraphListByPage={this.fetchGraphListByPage}
									pathId={id}
									location={location}
								/>
							</Tabs.TabPane>
							{tabPaneList.map((item) => {
								return (
									<Tabs.TabPane key={item.id} tab={item.name}>
										<GraphList
											graphCategoryId={item.id}
											tabPaneList={tabPaneList}
											list={graphList}
											total={graphTotal}
											current={this.state.current}
											graphLoading={graphLoading}
											fetchGraphListByPage={this.fetchGraphListByPage}
											pathId={id}
											location={location}
										/>
									</Tabs.TabPane>
								);
							})}
						</Tabs>
					</div>
					<TabPaneModal onRef={(ref) => (this.TabPaneModal = ref)} tabPaneList={tabPaneList} getTabList={this.getTabList} id={id} />
					<EditPaneModal onRef={ref => this.EditPaneModalRef = ref} setCategory={this.setCategory} getTabList={this.getTabList} />
					<ReferenceTemplate onRef={ref => this.referenceTemplateRef = ref} />
				</Suspense>
			</GridContent>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(TabCategory);
